<template>
  <div class="add-role">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ title }}</span>
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="activeStep">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <div v-show="activeStep === 1" v-loading="loading" class="form-container">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form ref="roleForm" class="form-box" :model="roleForm" :rules="roleRules">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="roleForm.roleName" />
            </el-form-item>
            <el-form-item label="角色描述" prop="remark">
              <el-input v-model="roleForm.remark" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div v-show="activeStep === 2" class="form-container">
        <div class="title">权限配置</div>
        <div class="form">
          <div class="tree-wrapper">
            <div v-for="item in permissionList" :key="item.id" class="tree-item">
              <!-- title -->
              <div class="tree-title">{{ item.title }}</div>
              <!-- 树形结构 -->
              <el-tree
                ref="tree"
                :props="{ label: 'title' }"
                :data="item.children"
                show-checkbox
                :default-expand-all="true"
                node-key="id"
                check-on-click-node
                :expand-on-click-node="false"
              />
            </div>
          </div>
        </div>
      </div>
      <div v-show="activeStep === 3" class="form-container">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ roleForm.roleName }}</div>
            <div class="form-item">角色描述：{{ roleForm.remark }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div v-for="item in diabledTree" :key="item.id" class="tree-item">
                <div class="tree-title">{{ item.title }}</div>
                <el-tree
                  ref="diabledTree"
                  :data="item.children"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  :highlight-current="false"
                  :props="{ label: 'title' }"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button v-show="activeStep > 1" @click="activeStep--">上一步</el-button>
        <el-button v-show="activeStep < 3" type="primary" @click="next">下一步</el-button>
        <el-button v-show="activeStep === 3" type="primary" @click="submit">完成</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { getAllPermission, addRole, updateRole } from '@/api/system/role'
import { addDisabled } from '@/utils/index'
export default {
  data() {
    return {
      activeStep: 1, // 当前步骤
      roleForm: {
        roleName: '',
        remark: ''
      }, // 角色表单
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      }, // 角色表单验证规则
      permissionList: [], // 权限列表
      perms: [], // 存储选中的权限点
      diabledTree: [], // 禁用的树形结构
      loading: true
    }
  },
  computed: {
    title() {
      return this.$route.query.type === 'edit' ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getAllPermission()
  },
  methods: {
    // 下一步
    async next() {
      // 校验角色信息
      if (this.activeStep === 1) {
        await this.$refs.roleForm.validate()
      } else if (this.activeStep === 2) {
        this.perms = []
        this.$refs.tree.forEach((item, index) => {
          this.perms.push(item.getCheckedKeys())
        }) // 存储选中的权限点
        // console.log(this.perms)
        // this.$nextTick(() => {
        this.$refs.diabledTree.forEach((item, index) => {
          item.setCheckedKeys(this.perms[index])
        //   })
        }) // 调用setCheckedKeys方法
        // 校验权限信息 不能为空
        if (this.perms.flat().length === 0) {
          this.$message({
            type: 'error',
            message: '请至少选择一个权限点'
          })
          return
        }
      }
      this.activeStep++
    },
    // 获取角色详情
    async getRoleDetail(data) {
      const { roleId, roleName, remark, perms } = data
      this.roleForm = {
        roleName,
        remark,
        roleId
      }
      this.perms = perms
      this.$nextTick(() => {
        this.$refs.tree.forEach((item, index) => {
          item.setCheckedKeys(this.perms[index])
        })
      })
      this.loading = false
    },
    // 获取权限列表(树形)
    async getAllPermission() {
      const res = await getAllPermission()
      this.permissionList = res
      this.diabledTree = addDisabled(JSON.parse(JSON.stringify(res)))
      // console.log(res)
      if (this.$route.query.type === 'edit') {
        this.getRoleDetail(JSON.parse(localStorage.getItem('roleInfo')))
      }
    },
    // 确认提交
    async submit() {
      if (this.$route.query.type === 'edit') {
        // console.log(this.roleForm)
        await updateRole({
          ...this.roleForm,
          perms: this.perms

        })
        this.$message.success('修改成功')
      } else {
        await addRole({
          ...this.roleForm,
          perms: this.perms
        })
        this.$message.success('添加成功')
      }
      localStorage.removeItem('roleInfo')
      this.$router.push('/sys/role')
    }
  }
}
</script>
<style scoped lang="scss">
.add-role {
    background-color: #f4f6f8;
    height: 100vh;

    .add-header {
        display: flex;
        justify-content: space-between;
        padding: 0 20px;
        height: 64px;
        line-height: 64px;
        font-size: 16px;
        font-weight: bold;
        background-color: #fff;

        .left {
            span {
                margin-right: 4px;
            }

            .arrow {
                cursor: pointer;
            }
        }

        .right {
            text-align: right;
        }
    }

    .add-main {
        position: fixed;
        top: 64px;
        bottom: 88px;
        width: 100%;
        overflow-y: auto;
        background: #f4f6f8;
        padding: 20px 230px;
        display: flex;

        .step-container {
            height: 400px;
            width: 200px;
        }

        .form-container {
            flex: 1;
            background-color: #fff;
            overflow-y: auto;

            .title {
                height: 60px;
                line-height: 60px;
                padding-left: 20px;
            }

            .form {
                margin-bottom: 20px;
                padding: 20px 65px 24px;

                .el-form {
                    display: flex;
                    flex-wrap: wrap;
                }

                .info {
                    font-size: 14px;
                    color: #666;

                    .form-item {
                        margin-bottom: 20px;
                    }
                }
            }

            .form-box {
                width: 600px;
                display: flex;
                flex-direction: column;
            }
        }
    }

    .add-footer {
        position: fixed;
        bottom: 0;
        width: 100%;
        padding: 24px 50px;
        color: #000000d9;
        font-size: 14px;
        background: #fff;
        text-align: center;
        z-index: 10001;
    }

    .tree-wrapper {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;

        .tree-item {
            padding: 0px 4px;
            text-align: center;

            .tree-title {
                background: #f5f7fa;
                text-align: center;
                padding: 10px 0;
                margin-bottom: 12px;
            }
        }
    }
}
</style>
